<script setup lang="ts" name="PlayGround">
/*
  vant表单验证
  1：表单元素绑定相应的值
  2: 写规则
     rules:{
      username:[
        {required:true,message:'信息',trigger:'onChange'},
        {pattern:正则,message:'信息',trigger:'onChange'},
        {validator:(value)=>{return boolean },message:'错误信息',trigger:'onChange'}    
    ]  as FieldRule[]
     }
  3:使用规则
       van-filed :rules='rules.username'
  4:触发验证
     van-button @click=submit
     const form=ref()
     const submit=async ()=>{
      // form.value.validate().then().catch()
    await  form.value.validate()
    // 成功代码
     }

*/
import type { FieldRule } from 'vant'
import { ref } from 'vue'

const formData = ref({
  username: '',
  password: ''
})

const rules: {
  username: FieldRule[]
  password: FieldRule[]
} = {
  username: [{ required: true, message: '必填', trigger: 'onChange' }],
  password: [{ required: true, message: '必填', trigger: 'onChange' }]
}
// const rules = {
//   username: [{ required: true, message: '必填', trigger: 'onChange' }] as FieldRule[],
//   password: [{ required: true, message: '必填', trigger: 'onChange' }] as FieldRule[]
// }
// const rules: any = {
//   username: [{ required: true, message: '必填', trigger: 'onChange' }],
//   password: [{ required: true, message: '必填', trigger: 'onChange' }]
// }
const form = ref()
const submit = async () => {
  // this.$refs.form.validate()
  try {
    await form.value.validate('username')
    console.log('成功')
  } catch (e) {
    console.log(e, '失败')
  }
}
</script>

<template>
  <div class="app-page">
    <!-- <van-form @submit="submit">
      <van-field label="用户名" v-model="formData.username" :rules="rules.username"></van-field>
      <van-field label="密码" v-model="formData.password" :rules="rules.password"></van-field>
      <van-button native-type="submit">提交</van-button>
    </van-form> -->
    <van-form ref="form">
      <van-field
        label="用户名"
        name="username"
        v-model="formData.username"
        :rules="rules.username"
      ></van-field>
      <van-field label="密码" v-model="formData.password" :rules="rules.password"></van-field>
    </van-form>
    <van-button @click="submit">提交</van-button>
  </div>
</template>

<style lang="scss" scoped></style>
